//
//  RxMoyaViewController.swift
//  test-ios
//
//  Created by wyz5204 on 2023/4/24.
//

import UIKit
import Moya
import SwiftyJSON
import RxSwift

class RxMoyaTableCell : AbstractTableViewCell<String>{
    
    lazy var title : UILabel = {
        return UILabel()
    }()
    
    override func initView() {
        self.title.addTo(self.contentView) { view in
            view.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
        }
    }
    
    override func initBinder(_ view: UITableView, _ data: String, _ index: IndexPath) {
        self.title.setTitleAndColor(data)
    }
}

class RxMoyaViewController: MVVMBaseViewController<RxMoyaViewModel> {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        // view
        let tableView = UITableView()
        tableView.register(RxMoyaTableCell.self, forCellReuseIdentifier: "Cell")
        tableView.addTo(self.view) { view in
            view.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
        }
        // api
        let myProvider = MoyaProvider<DoubanAPI>(plugins: [MoyaLoggingPlugin()])
        
        // 网络请求
        let data = myProvider.rx.request(.channels)
            .mapJSON()
            .map({ data -> [[String:Any]] in
                if let json = data as? [String: Any],
                   let channels = json["channels"] as? [[String: Any]] {
                    return channels
                }else{
                    return []
                }
            })
            .asObservable()
        
        // 数据绑定
        data.bind(to: tableView.rx.items) { (tableView, row, element) in
            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! RxMoyaTableCell
            cell.initBinder(tableView , element["name"] as! String , IndexPath.init(row: row, section: 0))
            return cell
        }.disposed(by: rx.disposeBag)
        
        // 数据驱动
        tableView.rx.itemSelected.asObservable().subscribe { indexPath in
            print("onNext" , indexPath)
        } onError: { error in
            print("onError",error)
        } onCompleted: {
            print("onCompleted")
        } onDisposed: {
            print("onDisposed" )
        }.disposed(by: rx.disposeBag)
        
        tableView.rx.itemSelected.flatMap {
            [weak table = tableView] indexPath -> Observable<Any> in
            guard let view = table else {
                return Observable.empty()
            }
            return Observable.just(try view.rx.model(at: indexPath))
        }.subscribe { event in
            print(event)
        }.disposed(by: rx.disposeBag)
//
//        //单元格点击
//        tableView.rx.modelSelected([String: Any].self)
//            .map{ $0["channel_id"] as! String }
//            .flatMap{ DouBanProvider.rx.request(.playlist($0)) }
//            .mapJSON()
//            .subscribe(onNext: {[weak self] data in
//                //解析数据，获取歌曲信息
//                if let json = data as? [String: Any],
//                   let musics = json["song"] as? [[String: Any]]{
//                    let artist = musics[0]["artist"]!
//                    let title = musics[0]["title"]!
//                    let message = "歌手：\(artist)\n歌曲：\(title)"
//                    //将歌曲信息弹出显示
//                    self?.showAlert(title: "歌曲信息", message: message)
//                }
//            }).disposed(by: disposeBag)
    }
    
}


class RxMoyaViewModel : MVVMBaseViewModel{
    
    static let shared = RxMoyaViewModel()
    
}
